//获取应用实例
const app = getApp()
import Dialog from '../../lib/vant/dialog/dialog';
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
const cityUtil = require('../../utils/city.js');
var newarr = cityUtil.getDateByLevelType(1);
Page({
  data: {
    pageSize: 20,
    pageNum: 1,
    //控制排序选项选中属性
    pxnum: 0,
    //控制日期选项选中属性
    rqnum: 0,
    //地区id
    cityid: '',
    //地区等级
    citylevel: '',
    //控制sx选项选中属性
    sxnum: 0,
    //用户纬度
    latitude: null,
    //用户经度
    longitude: null,
    // 屏幕滑动监控
    positionFixed: "",
    //更多按钮的弹窗显示和隐藏
    showModal: false,
    detailsList: [],
    //默认地址选择
    regionIndex: [],
    //默认地址
    regionArray: [['全部'], [], []], 
    //获取市级
    cityarr: null,
    //获取区/镇级
    region: null,
    //距离顶部位置
    fixwz: null,
//轮播图集合
    imgArr: [
      "https://image.xingqubaike.com:8443/minicard/interest/banner01.png", 
      'https://image.xingqubaike.com:8443/minicard/interest/banner02.png', 
      'https://image.xingqubaike.com:8443/minicard/interest/banner03.png',
      'https://image.xingqubaike.com:8443/minicard/interest/banner04.png',
      'https://image.xingqubaike.com:8443/minicard/interest/banner05.jpg',
      'https://image.xingqubaike.com:8443/minicard/interest/banner06.jpg',
      'https://image.xingqubaike.com:8443/minicard/interest/banner07.jpg'],
//标签集合
    colors: ["#069bd3", "#067faa", "#0272ea", "#08bdd7", "#26a70c", "#6aade2", "#42edc3", "#42ef4a", "#ffc607", "#1da88b", "#bbd341", "#fccc69", "#ed8442", "#7ec58b", "#fbe136", "#fea350", "#fd5660", "#069bd3"],
    qita: { "color": "#0d5094", "name": "兴趣专辑", "logo":""},
    lableList:[],
    //排序选项显示和隐藏控制
    pxshow: false,
    //日期选项显示和隐藏控制
    rqshow: false,
    //城市选项显示和隐藏控制
    sxshow: false,
  },
  //加载数据
  onReady: function (onLoad) {
    var _this = this;
    var arr = _this.data.regionArray
    for (var i = 0; i <= newarr.length - 1; i++) {
      arr[0].push(newarr[i].cityname)
    }
    _this.setData({
      regionArray: arr
    })
    var openid = app.globalData.logininfo.openid;
    var data = {};
    data.pageSize = _this.data.pageSize;
    data.pageNum = 1;
    data.sort1 = _this.data.pxnum;
    data.sort2 = _this.data.rqnum;
    data.cityid = _this.data.cityid;
    data.citylevel = _this.data.citylevel;
    data.screen = _this.data.sxnum;
    data.parentCatalogid = null;
    data.catalogid = null;
    data.search = null;
    data.latitude = null;
    data.longitude = null;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Interest_API_getAllInterestDetails, data).then(function (res) {
          if (res.code == 200) {
            var detailsList = res.result.list;
            _this.setData({
              detailsList: detailsList
            });
          }
        });
      });
    }else{
      util.post(api.Interest_getAllInterestDetails,data).then(function (res) {
        if (res.code == 200) {
          var detailsList = res.result.list;
          _this.setData({
            detailsList: detailsList
          });
        }
      });
    }
    util.post(api.Home_LevelOneCategoryUrl).then(function (res2) {
      if (res2.code == 200) {
        var arr = res2.result.list;
        for(var i=0;i<arr.length;i++){
          if (arr[i].catalogname=='自定义'){
            arr[i].catalogname = '其他'
          }
        }
        var cb = {};
        cb.id = "";
        cb.parentid = "0";
        cb.catalogname = "橙贝商城";
        cb.albumimage = '';
        arr.push(cb);
        _this.setData({
          lableList: arr
        })
        console.log(_this.data.lableList)
      }
    })
    var query = wx.createSelectorQuery();
    query.select('.top-fixed').boundingClientRect(function (rect) {
      var wz = parseInt(rect.height);
      _this.setData({
        fixwz: wz
      }) 
    }).exec()
  },
  //滑动监视
  onPageScroll: function (e) {
    var _this = this;
    var scrollTop = parseInt(e.scrollTop);
    var wz = _this.data.fixwz
    if (scrollTop >= wz) {
      _this.setData({
      positionFixed: "fixed"
      })
    } else {
      _this.setData({
        positionFixed: ""
      })
    }
  },
  //拉伸顶部刷新
  onPullDownRefresh: function(){
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var data = {};
    data.pageSize = _this.data.pageSize;
    data.pageNum = 1;
    data.sort1 = _this.data.pxnum;
    data.sort2 = _this.data.rqnum;
    data.cityid = _this.data.cityid;
    data.citylevel = _this.data.citylevel;
    data.screen = _this.data.sxnum;
    data.parentCatalogid = null;
    data.catalogid = null;
    data.search = null;
    data.latitude = _this.data.latitude;
    data.longitude = _this.data.longitude;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Interest_API_getAllInterestDetails, data).then(function (res) {
          if (res.code == 200) {
            var detailsList = res.result.list;
            _this.setData({
              detailsList: detailsList
            });
            console.log(detailsList)
          }
        });
      });
    } else {
      util.post(api.Interest_getAllInterestDetails, data).then(function (res) {
        if (res.code == 200) {
          var detailsList = res.result.list;
          _this.setData({
            detailsList: detailsList
          });
        }
      });
    }
    wx.stopPullDownRefresh();
  },

  onShow: function (options) {
    var _this = this;
    var distribution = app.globalData.distribution;
    if (distribution != null && distribution == true){
      _this.setData({
        sxnum: 5
      })
      app.globalData.distribution = false;
      console.log(app.globalData.distribution);
    }
  },

  //拉伸底部加载
  onReachBottom: function(){
    wx.showToast({
      title: '正在加载更多',
      icon: 'loading',
      duration: 1000
    })
    var _this = this;
    var page = parseInt(_this.data.pageNum + 1);
    _this.setData({
      pageNum: page
    })
    var openid = app.globalData.logininfo.openid;
    var data = {};
    data.pageSize = _this.data.pageSize;
    data.pageNum = page;
    data.sort1 = _this.data.pxnum;
    data.sort2 = _this.data.rqnum;
    data.cityid = _this.data.cityid;
    data.citylevel = _this.data.citylevel;
    data.screen = _this.data.sxnum;
    data.parentCatalogid = null;
    data.catalogid = null;
    data.search = null;
    data.latitude = _this.data.latitude;
    data.longitude = _this.data.longitude;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Interest_API_getAllInterestDetails, data).then(function (res) {
          if (res.code == 200) {
            var detailsList = res.result.list;
            var arr = _this.data.detailsList;
            for (var i = 0; i <= detailsList.length - 1; i++) {
              arr.push(detailsList[i])
            }
            _this.setData({
              detailsList: arr
            });
          }
        });
      });
    } else {
      util.post(api.Interest_getAllInterestDetails, data).then(function (res) {
        if (res.code == 200) {
          var detailsList = res.result.list;
          var arr = _this.data.detailsList;
          for (var i = 0; i <= detailsList.length - 1; i++) {
            arr.push(detailsList[i])
          }
          _this.setData({
            detailsList: arr
          });
        }
      });
    }
    wx.stopPullDownRefresh();
  },
  //点击获取排序选项id
  slectpx: function (e) {
    var _this = this
    _this.setData({
      pxnum: e.target.dataset.id,
      pxshow: false
    })
    wx.showTabBar({
    })
    _this.onPullDownRefresh();
    var query = wx.createSelectorQuery();
    query.select('.top-fixed').boundingClientRect(function (rect) {
      var wz = parseInt(rect.height);
      wx.pageScrollTo({
        scrollTop: wz + 1
      })
    }).exec();
  },
  //点击获取日期选项id
  slectrq: function (e) {
    var _this = this
    _this.setData({
      rqnum: e.target.dataset.id,
      rqshow: false
    })
    wx.showTabBar({
    })
    _this.onPullDownRefresh();
    var query = wx.createSelectorQuery();
    query.select('.top-fixed').boundingClientRect(function (rect) {
      var wz = parseInt(rect.height);
      wx.pageScrollTo({
        scrollTop: wz + 1
      })
    }).exec();
  },
  //点击获取筛选选项id
  slectsx: function (e) {
    var _this = this
    _this.setData({
      sxnum: e.target.dataset.id,
      sxshow: false
    })
    wx.showTabBar({
    })
    if (e.target.dataset.id == 6) {
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          const latitude = res.latitude
          const longitude = res.longitude
          _this.setData({
            latitude: latitude,
            longitude: longitude
          })
          _this.onPullDownRefresh();
        }
      })
    }else{
      _this.onPullDownRefresh();
    }
    var query = wx.createSelectorQuery();
    query.select('.top-fixed').boundingClientRect(function (rect) {
      var wz = parseInt(rect.height);
      wx.pageScrollTo({
        scrollTop: wz+1
      })
    }).exec();
  },
  //获取下级
  bindMultiPickerColumnChange: function (e) {
    var rColumn = e.detail.column
    if (rColumn == 0) {
      var rIndex = e.detail.value
      var rName = this.data.regionArray[0][rIndex]
      for (var i = 0; i <= newarr.length - 1; i++) {
        if (newarr[i].cityname == rName) {
          var rId = newarr[i].cityid
        }
      }
      this.setData({
        cityarr: cityUtil.getCityByFatherid(2, rId)
      })
      var arr = this.data.regionArray
      arr[1] = []
      arr[2] = []
      arr[1].push("全部")
      for (var i = 0; i <= this.data.cityarr.length - 1; i++) {
        arr[1].push(this.data.cityarr[i].cityname)
      }
      var qIndex = this.data.regionIndex
      qIndex[0] = rIndex
      qIndex[1] = 0
      qIndex[1] = 0
      this.setData({
        regionArray: arr,
        regionIndex: qIndex
      })
    }
    if (rColumn == 1) {
      if (this.data.cityarr != null && this.data.cityarr!=''){
      var rIndex = e.detail.value
      var rName = this.data.regionArray[1][rIndex]
      for (var i = 0; i <= this.data.cityarr.length - 1; i++) {
        if (this.data.cityarr[i].cityname == rName) {
          var rId = this.data.cityarr[i].cityid
        }
      }
      this.setData({
        region: cityUtil.getCityByFatherid(3, rId)
      })
      var arr = this.data.regionArray
      arr[2] = []
      arr[2].push("全部")
      for (var i = 0; i <= this.data.region.length - 1; i++) {
        arr[2].push(this.data.region[i].cityname)
      }
      var qIndex = this.data.regionIndex
      qIndex[1] = rIndex
      qIndex[2] = 0
      this.setData({
        regionArray: arr,
        regionIndex: qIndex
      })
     }
    }
    if (rColumn == 2) {
      if (this.data.region != null && this.data.region!=''){
      var rIndex = e.detail.value
      var rName = this.data.regionArray[2][rIndex]
      for (var i = 0; i <= this.data.region.length - 1; i++) {
        if (this.data.region[i].cityname == rName) {
          var rId = this.data.region[i].cityid
        }
      }
    }
    }
  },
  //确认地址
  bindMultiPickerChange: function (e) {
    var _this = this
    var sValue = e.detail.value
    var shengIndex = parseInt(sValue[0]) - 1
    var shiIndex = parseInt(sValue[1]) - 1
    var quIndex = parseInt(sValue[2]) - 1
    var addr = ''
    var addrLv = ''
    var cit = _this.data.cityarr
    var rig = _this.data.region
    if (quIndex >= 0) {
      var qu = rig[quIndex]
      addr = qu.cityid
      addrLv = 3
      _this.setData({
        cityid: addr,
        citylevel: addrLv
      })
      _this.onPullDownRefresh();
    } else if (shiIndex >= 0) {
      var shi = cit[shiIndex]
      addr = shi.cityid
      addrLv = 2
      _this.setData({
        cityid: addr,
        citylevel: addrLv
      })
      _this.onPullDownRefresh();
    } else if (shengIndex >= 0) {
      var sheng = newarr[shengIndex]
      addr = sheng.cityid
      addrLv = 1
      _this.setData({
        cityid: addr,
        citylevel: addrLv
      })
      _this.onPullDownRefresh();
    }else{
      _this.setData({
        cityid: null,
        citylevel: null
      })
      _this.onPullDownRefresh();
    }
    var query = wx.createSelectorQuery();
    query.select('.top-fixed').boundingClientRect(function (rect) {
      var wz = parseInt(rect.height);
      wx.pageScrollTo({
        scrollTop: wz + 1
      })
    }).exec();
  },
  //拓展导航模块的显示和隐藏
  showModalTap: function () {
    this.setData({
      showModal: true
    })
    wx.hideTabBar({
    })
  },
  hideModalTap: function () {
    this.setData({
      showModal: false
    })
    wx.showTabBar({
    })
  },
  //排序选项的显示和隐藏
  maxsortTap: function(){
    this.setData({
      pxshow: true
    })
    wx.hideTabBar({
    })
  },
  hidepxpop: function(){
    this.setData({
      pxshow: false
    })
    wx.showTabBar({
    })
  },
  //日期选项的显示和隐藏
  dateSortTap: function(){
    this.setData({
      rqshow: true
    })   
    wx.hideTabBar({
    })
  },
  hiderqpop: function(){
    this.setData({
      rqshow: false
    })
    wx.showTabBar({
    })
  },
  //筛选选项的显示和隐藏
  screenSortTap: function(){
    this.setData({
      sxshow: true
    })
    wx.hideTabBar({
    })
  },
  hidesxpop: function () {
    this.setData({
      sxshow: false
    })
    wx.showTabBar({
    })
  },
  // 点击蒙层隐藏
  onClose: function(){
    this.setData({
      pxshow:false,
      rqshow: false,
      sxshow: false
    })
    wx.showTabBar({
    })
  },
  //跳转详情页
  toParticulars: function (e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "../../interest/pages/interest/particulars/particulars"
    })
  },
  //跳转搜索页面
  intoSearch: function(){
    wx.navigateTo({
      url: "../../interest/pages/interest/search/search"
    })
  },
  //跳转类目页面
  gotolable: function (e) {
    var eId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "../../interest/pages/interest/classify/classify?c_id="+eId
    })
    wx.showTabBar({
    })
  },
  //跳转新建
  doPublish: function (event) {
    wx.navigateTo({
      url: '../../ucenter/pages/ucenter/personcenter/publish/publish?userid=1',
    })
  },
  /**
   * 进入圈子详情页面
   */
  navigateToCircleInfo: function (e) {
    var _this = this;
    var circleid = e.currentTarget.dataset.circleid;
    var openid = app.globalData.logininfo.openid;
    var getopenid = _this.data.getopenid;
    var data = {};
    data.circleid = circleid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.userIsCircleJoinQuery(api.Home_UserIsCircleJoinApiUrl, data);
      })
    } else {
      _this.userIsCircleJoinQuery(api.Home_UserIsCircleJoinUrl, data);
    }
  },
  /**
   * 校验用户是否为已加入的圈子：请求
   */
  userIsCircleJoinQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      var userIsCircleJoin = false;
      if (res.code == 200) {
        userIsCircleJoin = res.result.userIsCircleJoin;
      }
      console.log(userIsCircleJoin)
      if (userIsCircleJoin) {
        // 已加入
        wx.navigateTo({
          url: '../../ucenter/pages/ucenter/personcenter/editdetails/circleinteraction/circleinteraction?circleid=' + data.circleid,
        })
      } else {
        // 未加入
        wx.navigateTo({
          url: '../../ucenter/pages/ucenter/personcenter/editdetails/circledetails/circledetails?circleid=' + data.circleid,
        })
      }
    });
  },
})
